import { IGetDecisionFlowNodeVariablesRes } from '@/api';
import { MciDialog, MciInput, MciSubCard, MciSvgIcon, MciTable, MciTableColumn, MciEmpty } from '@/components/base';
import { useFormMode } from '@/components/base/Form/mode';
import { useCurrentNode } from '@/hooks/useCurrentNode';
import { useGraph } from '@/hooks/useGraph';
import { useDictStore } from '@/store/dict';
import { ElButton, ElEmpty, ElForm, ElFormItem, ElOption, ElPopconfirm, ElSelect } from 'element-plus';
import { activeNodeId } from '../BaseNode/state';
import './index.scss';
import { TVariables } from './types';

export const NodeVariableMangerForm = defineComponent({
  props: {
    edges: {
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const variables = ref<IGetDecisionFlowNodeVariablesRes>([]);
    const currentVariables = ref<TVariables>();
    const variableDialogVisible = ref(false);
    const dictStore = useDictStore();
    const { graph } = useGraph();
    const prevNodeVariables = ref<IGetDecisionFlowNodeVariablesRes>([]);
    const formRef = ref<InstanceType<typeof ElForm>>();
    const { fieldType } = useDictStore();
    const currentNode = useCurrentNode();
    let modifyIndex = -1;
    const formMode = useFormMode();

    const onConfirm = () => {
      formRef.value?.validate((valid) => {
        if (valid) {
          // 新增
          if (modifyIndex === -1) {
            variables.value.push({ ...currentVariables.value! });
          } else {
            variables.value.splice(modifyIndex, 1, { ...currentVariables.value! });
          }
          variableDialogVisible.value = false;
          saveGraphData();
        }
      });
    };

    const saveGraphData = () => {
      currentNode.saveCurrentPrivateVariables(variables.value);
    };

    const varNameValidator = (rule: any, value: string, callback: any) => {
      if (!value) {
        return callback(new Error('请输入变量名称'));
      }
      if (prevNodeVariables.value.some((item) => item.varName === value)) {
        return callback(new Error('变量名称重复, 请更换其他名称'));
      }
      if (variables.value.some((item, index) => item.varName === value && index !== modifyIndex)) {
        return callback(new Error('变量名称重复, 请更换其他名称'));
      }
      callback();
    };

    watch(variableDialogVisible, (val) => {
      if (!val) {
        formRef.value?.resetFields();
      }
    });

    onMounted(() => {
      dictStore.getDictFieldType();
      const node = graph.value?.getCellById(activeNodeId.value);
      variables.value = node?.getData()?.variables || [];
    });

    // const getVariables = () => {
    //   if (!activeNodeId.value) {
    //     MciNotification.error('请先选择节点');
    //     return;
    //   }
    //   getDecisionFlowNodeVariables({ nodeId: activeNodeId.value }).then((res) => {
    //     variables.value = res;
    //   });
    // };

    // onMounted(() => {
    //   getVariables();
    // });

    return () => {
      return (
        <div onClick={(e) => e.stopPropagation()} class="flex flex-col">
          <div class="operation-left flex flex-col">
            <MciSubCard class="py-8" title="当前节点私有变量">
              {{
                titleRight() {
                  if (formMode?.mode === 'view') return null;
                  return (
                    !props.edges && (
                      <ElButton
                        onClick={() => {
                          modifyIndex = -1;
                          currentVariables.value = {} as TVariables;
                          variableDialogVisible.value = true;
                        }}
                        link>
                        <MciSvgIcon color="var(--color-grey-5)" width={18} height={18} name="plus" />
                        <span class="text-value-14 pr-12">添加变量</span>
                      </ElButton>
                    )
                  );
                },
                default() {
                  return (
                    <div class="var-list">
                      {/* {prevNodeVariables.value.length > 0 && (
                        <div class="mb-20">
                          {<div class="text-value-14">前置节点输出变量</div>}
                          {prevNodeVariables.value.map((item) => {
                            return (
                              <VariableItem
                                data={item}
                                onClick={() => {
                                  currentVariables.value = { ...item };
                                  variableDialogVisible.value = true;
                                }}
                                key={item.varName! + item.varType + item.id}
                              />
                            );
                          })}
                        </div>
                      )} */}
                      {variables.value.length > 0 && (
                        <MciTable data={variables.value}>
                          <MciTableColumn label="变量名称" prop="varName" />
                          <MciTableColumn label="变量中文名" prop="varLabel" />
                          <MciTableColumn label="类型" prop="varType">
                            {(scope: any) => (
                              <>
                                <p>{dictStore.fieldTypeMap[scope.row.varType!]}</p>
                              </>
                            )}
                          </MciTableColumn>
                          <MciTableColumn label="默认值" prop="initValue" />
                          {formMode?.mode === 'edit' && (
                            <MciTableColumn width={80} label="操作">
                              {(scope: any) => (
                                <div class="var-item__action flex gap-8 py-8 justify-center" onClick={(e) => e.stopPropagation()}>
                                  <MciSvgIcon
                                    onClick={() => {
                                      currentVariables.value = { ...scope.row };
                                      variableDialogVisible.value = true;
                                      modifyIndex = scope.$index;
                                    }}
                                    width={18}
                                    height={18}
                                    class="cursor-pointer"
                                    name="edit"
                                  />
                                  <ElPopconfirm
                                    onConfirm={() => {
                                      variables.value.splice(variables.value.indexOf(scope.row), 1);
                                      saveGraphData();
                                    }}
                                    confirm-button-text="确定"
                                    cancel-button-text="取消"
                                    title="确定删除?">
                                    {{
                                      reference() {
                                        return <MciSvgIcon width={18} height={18} class="cursor-pointer" name="close" />;
                                      }
                                    }}
                                  </ElPopconfirm>
                                </div>
                              )}
                            </MciTableColumn>
                          )}
                        </MciTable>
                      )}
                      {/* {!variables.value.length ? <ElEmpty class="!py-0" imageSize={70} description="暂无变量" /> : null} */}
                      {!variables.value.length ?  <MciEmpty tipText={'暂无数据'} /> : null}
                    </div>
                  );
                }
              }}
            </MciSubCard>
          </div>

          <MciDialog width={540} v-model={variableDialogVisible.value}>
            {{
              default() {
                return (
                  <ElForm ref={formRef} model={currentVariables.value} labelPosition="top">
                    <div class="flex justify-between gap-20">
                      <ElFormItem
                        class="flex-1"
                        required
                        label="变量名称"
                        prop="varName"
                        rules={[
                          {
                            validator: varNameValidator,
                            trigger: ['change', 'blur']
                          }
                        ]}>
                        <MciInput v-model={currentVariables.value!.varName} placeholder="请输入变量名称" />
                      </ElFormItem>

                      <ElFormItem class="flex-1" required label="变量中文名" prop="varLabel">
                        <MciInput v-model={currentVariables.value!.varLabel} placeholder="请输入变量中文名" />
                      </ElFormItem>
                    </div>
                    <ElFormItem class="flex-1" required label="变量类型" prop="varType">
                      <ElSelect placeholder="请选择变量类型" class="w-full" v-model={currentVariables.value!.varType}>
                        {fieldType.map((item) => (
                          <ElOption
                            key={item.dictName!}
                            class="w-230"
                            disabled={item.enable === false}
                            label={item.dictName}
                            value={item.dictCode!}
                          />
                        ))}
                      </ElSelect>
                    </ElFormItem>
                    <ElFormItem label="变量默认值" prop="initValue">
                      <MciInput
                        type="textarea"
                        rows={3}
                        v-model={currentVariables.value!.initValue}
                        placeholder="请输入变量默认值"
                      />
                    </ElFormItem>
                  </ElForm>
                );
              },
              footer() {
                return (
                  <>
                    <ElButton onClick={() => (variableDialogVisible.value = false)}>取消</ElButton>
                    <ElButton type="primary" onClick={onConfirm}>
                      确定
                    </ElButton>
                  </>
                );
              }
            }}
          </MciDialog>
        </div>
      );
    };
  }
});
